package com.youkeyi.ddy.cloud.application.business.crm.support.service.impl;

import com.youkeyi.ddy.cloud.application.business.crm.support.service.UserSupportService;
import com.youkeyi.ddy.cloud.common.api.application.system.user.dto.SystemUserListByOrgCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.system.user.dto.SystemUserListByOrgItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.system.user.param.SystemUserListByOrgCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.pub.mapping.PublicMappingCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.pub.mapping.dto.PublicMappingListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.mapping.dto.PublicMappingListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.mapping.param.PublicMappingQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.pub.organization.PublicOrganizationCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.pub.organization.dto.PublicOrganizationListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.organization.dto.PublicOrganizationListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.organization.param.PublicOrganizationQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.pub.position.PublicPositionCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.pub.position.dto.PublicPositionListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.position.dto.PublicPositionListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.position.param.PublicPositionQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.pub.user.PublicUserCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.pub.user.dto.PublicUserListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.user.param.PublicUserQueryCloudParam;
import com.youkeyi.ddy.cloud.common.config.TestCorpConfig;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyCloudBasicPublicConstant;
import com.youkeyi.ddy.cloud.common.context.YoukeyiSystemContext;
import com.youkeyi.ddy.cloud.common.enums.ResponseCodeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * UserSupportServiceImpl
 *
 * @Author liuxiawang
 * @Date 2024/5/11 2:09 PM
 * @Location shenzhen.china
 */
@Service
public class UserSupportServiceImpl implements UserSupportService {

    @Autowired
    private PublicUserCloudService publicUserCloudService;
    @Autowired
    private PublicOrganizationCloudService publicOrganizationCloudService;
    @Autowired
    private PublicPositionCloudService publicPositionCloudService;
    @Autowired
    private PublicMappingCloudService publicMappingCloudService;

    @Override
    public SystemUserListByOrgCloudDto listUserByOrg(SystemUserListByOrgCloudParam param) {
        SystemUserListByOrgCloudDto dto = new SystemUserListByOrgCloudDto();
        String corpKey = YoukeyiSystemContext.getCorpPrimaryKey();
        if (StringUtils.isBlank(corpKey)) {
            dto.setErrorMessage(ResponseCodeEnum.TOKEN_INVALID.getMessage());
            return dto;
        }
        if (null == param) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }

        Map<String, PublicOrganizationListItemCloudDto> organizationMap = new HashMap<>();
        Map<String, PublicPositionListItemCloudDto> positionMap = new HashMap<>();
        Map<String, String> mappingMap = new HashMap<>();

        PublicOrganizationQueryCloudParam organizationQueryCloudParam = new PublicOrganizationQueryCloudParam();
        organizationQueryCloudParam.setOrganizationPrimaryKeys(param.getOrganizationPrimaryKeys());
        // 非测试主体就查询的时候剔除测试主体
        if (!TestCorpConfig.TestCorpKey.contains(corpKey)) {
            organizationQueryCloudParam.setNotInOrganizationPrimaryKeys(Arrays.asList(TestCorpConfig.TestCorpKey.split("\\|")));
        }
        PublicOrganizationListCloudDto organizations = publicOrganizationCloudService.query(organizationQueryCloudParam);
        if (null != organizations && CollectionUtils.isNotEmpty(organizations.getRows())) {
            organizationMap.putAll(organizations.getRows().stream().collect(Collectors.toMap(PublicOrganizationListItemCloudDto::getOrganizationPrimaryKey, Function.identity(), (k1, k2) -> k1)));

            // 岗位信息
            PublicPositionQueryCloudParam positionQueryCloudParam = new PublicPositionQueryCloudParam();
            positionQueryCloudParam.setOrganizationKeys(organizations.getRows().stream().map(PublicOrganizationListItemCloudDto::getOrganizationPrimaryKey).collect(Collectors.toList()));
            PublicPositionListCloudDto positionDtos = publicPositionCloudService.query(positionQueryCloudParam);
            if (null != positionDtos && CollectionUtils.isNotEmpty(positionDtos.getRows())) {
                positionMap.putAll(positionDtos.getRows().stream().collect(Collectors.toMap(PublicPositionListItemCloudDto::getPositionPrimaryKey, Function.identity(), (k1, k2) -> k1)));

                // 查询用户
                PublicMappingQueryCloudParam publicMappingQueryCloudParam = new PublicMappingQueryCloudParam();
                publicMappingQueryCloudParam.setMappingType(YoukeyiDdyCloudBasicPublicConstant.PUBLIC_MAPPING_TYPE_USER_POSITION.value());
                publicMappingQueryCloudParam.setKeyType(YoukeyiDdyCloudBasicPublicConstant.PUBLIC_MAPPING_KEY_TYPE_TARGET.value());
                publicMappingQueryCloudParam.setKeys(positionDtos.getRows().stream().map(PublicPositionListItemCloudDto::getPositionPrimaryKey).collect(Collectors.toList()));
                PublicMappingListCloudDto publicMappingDtos = publicMappingCloudService.query(publicMappingQueryCloudParam);
                if (null != publicMappingDtos && CollectionUtils.isNotEmpty(publicMappingDtos.getRows())) {
                    mappingMap.putAll(publicMappingDtos.getRows().stream().collect(Collectors.toMap(PublicMappingListItemCloudDto::getSourceKey, PublicMappingListItemCloudDto::getTargetKey, (k1, k2) -> k1)));

                    PublicUserQueryCloudParam userQueryCloudParam = new PublicUserQueryCloudParam();
                    userQueryCloudParam.setUserPrimaryKeys(publicMappingDtos.getRows().stream().map(PublicMappingListItemCloudDto::getSourceKey).collect(Collectors.toList()));
                    PublicUserListCloudDto userDtos = publicUserCloudService.query(userQueryCloudParam);
                    if (null != userDtos && CollectionUtils.isNotEmpty(userDtos.getRows())) {
                        List<SystemUserListByOrgItemCloudDto> items = new ArrayList<>();
                        userDtos.getRows().forEach(user -> {
                            SystemUserListByOrgItemCloudDto item = new SystemUserListByOrgItemCloudDto();
                            item.setUserPrimaryKey(user.getUserPrimaryKey());
                            item.setUserCode(user.getCode());
                            item.setUserName(user.getName());
                            item.setUserNickName(user.getNickName());
                            item.setUserPhone(user.getPhone());
                            item.setUserEmail(user.getEmail());
                            item.setUserAvatarUrl(user.getAvatarUrl());
                            if (mappingMap.containsKey(user.getUserPrimaryKey())) {
                                if (positionMap.containsKey(mappingMap.get(user.getUserPrimaryKey()))) {
                                    PublicPositionListItemCloudDto position = positionMap.get(mappingMap.get(user.getUserPrimaryKey()));
                                    item.setPositionPrimaryKey(position.getPositionPrimaryKey());
                                    item.setPositionName(position.getName());
                                    item.setPositionCode(position.getCode());

                                    if (organizationMap.containsKey(position.getOrganizationKey())) {
                                        PublicOrganizationListItemCloudDto organization = organizationMap.get(position.getOrganizationKey());
                                        item.setOrganizationPrimaryKey(organization.getOrganizationPrimaryKey());
                                        item.setOrganizationName(organization.getName());
                                        item.setOrganizationCode(organization.getCode());
                                    }
                                }
                            }
                            items.add(item);
                        });
                        dto.setRows(items);
                    }
                }
            }
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }
}
